const DEFAULT_SCRIPT_URL = "https://mc.yandex.ru/metrika/tag.js";
const DEFAULT_WATCH_URL = "https://mc.yandex.ru/watch/";

module.exports = function (context, options) {
  const {
    websitePrivacyPolicyURL,
    counterID,
  } = options;

  if (!counterID) {
    throw new Error(
      `You need to specify "counterID" field in plugin options to use docusaurus-plugin-yandex-metrica.`
    );
  }
  const cookieconsent =
    `<!-- Cookie Consent by TermsFeed https://www.TermsFeed.com -->
  <script type="text/javascript" src="/scripts/cookie-consent/4.1.0/cookie-consent.js" charset="UTF-8"></script>
  <script type="text/javascript" charset="UTF-8">
  document.addEventListener('DOMContentLoaded', function () {
  cookieconsent.run({"notice_banner_type":"simple","consent_type":"implied","palette":"dark","language":"ru","page_load_consent_levels":["strictly-necessary","functionality","tracking","targeting"],"notice_banner_reject_button_hide":false,"preferences_center_close_button_hide":false,"page_refresh_confirmation_buttons":false,"website_privacy_policy_url":"`+websitePrivacyPolicyURL+`"});
  });
  </script>
  
  <!-- Yandex.Metrika -->
  <!-- Yandex.Metrika counter -->
  <script type="text/plain" data-cookie-consent="tracking" >
     (function(m,e,t,r,i,k,a){m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)};
     m[i].l=1*new Date();
     for (var j = 0; j < document.scripts.length; j++) {if (document.scripts[j].src === r) { return; }}
     k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)})
     (window, document, "script", "` +
    DEFAULT_SCRIPT_URL +
    `", "ym");
  
     ym(`+counterID+`, "init", {
          clickmap:true,
          trackLinks:true,
          accurateTrackBounce:true
     });
  </script>
  <noscript><div><img src="`+DEFAULT_WATCH_URL+``+counterID+`" style="position:absolute; left:-9999px;" alt="" /></div></noscript>
  <!-- /Yandex.Metrika counter -->
  <!-- end of Yandex.Metrika-->
  
  <noscript>Free cookie consent management tool by <a href="https://www.termsfeed.com/">TermsFeed</a></noscript>
  <!-- End Cookie Consent by TermsFeed https://www.TermsFeed.com -->`;
  return {
    name: "cookieconsent-plugin",
    injectHtmlTags({ content }) {
      return {
        preBodyTags: [cookieconsent],
      };
    },
  };
};
